package com.xmg.nio.groupchart;

import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {
    private final String HOST = "127.0.0.1";
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel channel;
    private String username;

    public GroupChatClient() {
        try {
            selector = Selector.open();
            channel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            username = channel.getLocalAddress().toString().substring(1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendInfo(String info){
        String msg = username + " 说："+info;
        try {
            channel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readInfo(){
        try {
            int readCount = selector.select();
            if(readCount>0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer allocate = ByteBuffer.allocate(1024);
                        channel.read(allocate);
                        String msg = new String(allocate.array());
                        System.out.println(msg);
                    }
                    iterator.remove();
                }
            }else{
//                System.out.println("没有可以使用的通道");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();

        new Thread(()->{
            while (true) {
                client.readInfo();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            client.sendInfo(s);
        }
    }
}
